<template>
	<view class="cover_wrapper">
		<view class="p_font_24 p_flex12 p_t_96 p_b_36">
			<view class="p_color_fff">封底</view>
			<view class="p_color_fff">封面</view>
		</view>
		<view class="p_lr_24">
			<view class="cover_content p_flex2">
				<view class="cover_main"></view>
				<view class="cover_line"></view>
				<view class="cover_main my_canvas" id="my-canvas">
					<movable-area class="cover_area" v-if="isShow">
						<movable-view class="cover_view" :x="x" :y="y" direction="all" :damping="1000"
							@change="onChange">
							<view class="p_color_7a p_font_28" id="textInput" v-show="!coverContent">输入封面文字</view>
							<view :class="[textTypeList[textTypeIndex].c, textSizeList[textSizeIndex].c]">
								{{coverContent}}
							</view>
						</movable-view>
					</movable-area>
					<view
						:style="'position: absolute;top:' + (isChange?old.y: y) + 'px;left: ' + (isChange?old.x: x) + 'px;'"
						:class="[textTypeList[textTypeIndex].c, textSizeList[textSizeIndex].c]" class="my_draw_canvas"
						data-type="text" :data-text="coverContent" v-else>{{coverContent}}
					</view>
				</view>
			</view>
		</view>
		<view class="cover_input">
			<input placeholder="输入封面文字，最多14个字符" maxlength="14" placeholder-class="p_font_28 p_color_7a"
				class="p_font_28 p_color_e8 p_flex_2" v-model="coverInputContent" />
			<image src="https://dy.sykj365.com/uploads/mini/xuanzhong1@2x.png" class="p_img_48 p_margin_l_8" @click="getSureText(0)">
			</image>
		</view>
		<view class="p_flex cover_type">
			<view class="p_font_28 p_color_b2 type_label">文字排版</view>
			<view class="type_content p_font_26 p_flex_1">
				<view v-for="(item, index) in textTypeList" :class="{'active': textTypeIndex === index}"
					@click="getSureText(1, index)">{{item.name}}
				</view>
			</view>
		</view>
		<view class="p_flex cover_size">
			<view class="p_font_28 p_color_b2 type_label">字体大小</view>
			<view class="type_content p_font_26 p_flex_1">
				<view v-for="(item, index) in textSizeList" :class="{'active': textSizeIndex === index}"
					@click="getSureText(2, index)">{{item.name}}
				</view>
			</view>
		</view>
		<view class="p_btn" @click="getCaverImage">
			<view>确定</view>
		</view>
		<!-- 获取宽度和高度 -->
		<view style="height: 54rpx;position: fixed;z-index: -1;" id="coverView"></view>
		<view style="display: inline-block;position: fixed;z-index: -1;" id="coverTextView">{{coverContent}}</view>
		<!-- 绘制图片 -->
		<canvas id="myCanvas" canvas-id="myCanvas" style="width: 870px;height: 1225px;background-color: #fff;position: fixed;z-index: -99999;opacity: 0;top: -1000px;"></canvas>
		<!-- <image :src="imgUrl" style="width: 1000px;height: 500px;" mode="widthFix"></image> -->
		<!-- <canvas id="myCanvas" canvas-id="myCanvas" style="position: fixed;z-index: -99999;opacity: 0;top: -1000px;width: 348rpx;height: 490rpx;"></canvas> -->
	</view>
</template>

<script>
	import Wxml2Canvas from 'wxml2canvas';

	export default {
		data() {
			return {
				x: 0,
				y: 0,
				old: {
					x: 0,
					y: 0
				},
				coverContent: '',
				coverInputContent: '',
				textTypeIndex: 0,
				textTypeList: [{
					id: 0,
					name: '文字横排',
					c: ''
				}, {
					id: 1,
					name: '文字竖排',
					c: 'p_text_verticle'
				}],
				textSizeIndex: 0,
				textSizeList: [{
					name: '小',
					c: 'p_font_24'
				}, {
					name: '较小',
					c: 'p_font_36'
				}, {
					name: '中',
					c: 'p_font_48'
				}, {
					name: '大',
					c: 'p_font_64'
				}],
				isShow: false,
				coverData: {},
				isChange: false,
				isFirstText: true, // 是否第一次输入文字
				imgUrl: ''
			}
		},
		onLoad(o) {
			this.getViewInfo();

			if (o.coverInfo) {
				let e = JSON.parse(o.coverInfo);
				if (e.url) {
					this.coverContent = e.content;
					this.coverInputContent = this.coverContent;
					this.textTypeIndex = e.textTypeIndex;
					this.textSizeIndex = e.textSizeIndex;
					this.isFirstText = false;

					setTimeout(() => {
						this.x = e.x;
						this.y = e.y;
						this.old.x = this.x;
						this.old.y = this.y;
						this.isShow = true;
					}, 0)
				}
			}
		},
		onShow() {

		},
		methods: {
			onChange(e) {
				this.old.x = e.detail.x;
				this.old.y = e.detail.y;
				this.isChange = true;
			},
			getViewInfo() {
				const self = this;
				const query = wx.createSelectorQuery();
				query.selectAll('#coverView').boundingClientRect();
				query.exec(function(res) {
					if (!uni.getStorageSync('coverTextData')) {
						self.y = res[0][0].height;
						self.isShow = true;
						setTimeout(() => {
							self.getTextInfo();
						}, 0)
					}
				})
			},
			getTextInfo() {
				let self = this;
				let w_ = 0;

				const query = wx.createSelectorQuery();
				query.selectAll('#my-canvas').boundingClientRect();
				query.exec(function(res) {
					w_ = res[0][0].width;
				})

				if (!this.coverContent) {
					// 默认状态
					const query1 = wx.createSelectorQuery();
					query1.selectAll('#textInput').boundingClientRect();
					query1.exec(function(res) {
						if (!uni.getStorageSync('coverTextData')) {
							let x_ = res[0][0].width;
							self.x = (w_ - x_) / 2;
						}
					})
				}

				if (this.coverContent) {
					// 第一次输入文字时
					const query1 = wx.createSelectorQuery();
					query1.selectAll('#coverTextView').boundingClientRect();
					query1.exec(function(res) {
						if (!uni.getStorageSync('coverTextData')) {
							let x_ = res[0][0].width;
							self.x = (w_ - x_) / 2;
							self.isShow = true;

							self.old.x = self.x;
							self.old.y = self.y;
						}
					})
				}
			},
			getSureText(e, index) {
				if (e === 0) {
					this.coverContent = this.coverInputContent;
				} else if (e === 1) {
					this.textTypeIndex = index;
				} else if (e === 2) {
					this.textSizeIndex = index;
				}

				this.isShow = false;
				setTimeout(() => {
					if (!this.isFirstText) {
						this.x = this.old.x;
						this.y = this.old.y;
						this.isShow = true;
					} else {
						setTimeout(() => {
							this.getTextInfo();
						}, 0)
						this.isFirstText = false;
					}
				}, 0)
			},
			getCaverImage() {
				if (!this.coverContent) return getApp().getMsg('请输入封面文字');

				this.isShow = false;

				uni.showLoading();
				const that = this;
				const query = wx.createSelectorQuery().in(this);
				query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
					size: true,
					scrollOffset: true
				}, data => {
					let width = data.width;
					let height = data.height;
					
					const dpr = wx.getSystemInfoSync().pixelRatio;
					

					that.coverData = {
						width: width * dpr,
						height: height * dpr
					}

					setTimeout(() => {
						that.startDraw();
					}, 1500);
				}).exec();
			},
			startDraw() {
				let that = this;

				// 创建wxml2canvas对象
				let drawMyImage = new Wxml2Canvas({
					element: 'myCanvas', // canvas的id,
					obj: that, // 传入当前组件的this
					width: that.coverData.width,
					height: that.coverData.height,
					background: '#fff', // 生成图片的背景色
					logging: false, //日志
					scrollY: 0,
					scrollX: 0,
					useCORS: true, //跨域
					allowTaint: true,
					progress(percent) { // 进度
						// console.log(percent);
					},
					finish(url) { // 生成的图片
						console.log(url);
						that.imgUrl = url
						
						uni.uploadFile({
							url: that.$api.upload,
							filePath: url,
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								let result = JSON.parse(uploadFileRes.data);
						
								
							}
						});
						
						uni.setStorageSync('coverTextData', {
							url: url,
							content: that.coverContent,
							textTypeIndex: that.textTypeIndex,
							textSizeIndex: that.textSizeIndex,
							x: that.isChange ? that.old.x : that.x,
							y: that.isChange ? that.old.y : that.y
						});
						uni.hideLoading();
						uni.navigateBack();
					},
					error(res) { // 失败原因
						console.log(res);
						uni.hideLoading();
						uni.showToast({
							icon: 'error',
							title: '画图失败，请重试',
							duration: 2000
						});
					}
				}, this);
				let data = {
					// 获取wxml数据
					list: [{
						type: 'wxml',
						class: '.my_canvas .my_draw_canvas', // my_canvas要绘制的wxml元素根类名， **my_draw_canvas**单个元素的类名（所有要绘制的单个元素都要添加该类名）
						limit: '.my_canvas', // 要绘制的wxml元素根类名
						x: 0,
						y: 0
					}]
				}
				// 绘制canvas
				drawMyImage.draw(data, this);
			},			
		}
	}
</script>

<style lang="less">
	.cover_wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #222;
	}

	.cover_content {
		width: 100%;
		height: 490rpx;
		background-color: #fff;
	}

	.cover_line {
		height: 100%;
		width: 1px;
		border-left: 1px dashed #e8e8e8;
	}

	.cover_main {
		flex: 1;
		height: 100%;
		position: relative;
	}

	.cover_input {
		display: flex;
		align-items: center;
		padding-bottom: 34rpx;
		margin: 254rpx 64rpx 0;
		border-bottom: 1px solid rgba(255, 255, 255, 0.1);
	}

	.type_label {
		line-height: 62rpx;
		margin-right: 16rpx;
	}

	.type_content {
		display: flex;
		flex-wrap: wrap;

		view {
			color: #B2B2B2;
			padding: 8rpx 18rpx;
			border: 1px solid #3E3E3E;
			border-radius: 80rpx;
			margin: 4rpx 8rpx;
			min-width: 68rpx;
			text-align: center;

			&.active {
				color: #05B570;
			}
		}
	}

	.cover_type {
		margin: 58rpx 56rpx 0 64rpx;
	}

	.cover_size {
		margin: 40rpx 56rpx 0 64rpx;
	}

	.p_btn {
		margin-top: 78rpx;
	}

	.cover_area {
		width: 100%;
		height: 100%;
	}

	.cover_view {
		width: auto;
		height: auto;
	}
</style>